#!/bin/sh
#---help---
# Usage:
#   setup-sbase install [-d <dest>] [-f] [-v] [<applet>...]
#   setup-sbase uninstall [-d <dest>] [-v] [<applet>...]
#   setup-sbase status [-d <dest>]
#   setup-sbase (-h | -V)
#
# Install or uninstall applet symlinks for sbase-box.
#
# Arguments:
#   <applet>   Name of the applet(s) to (un)install or show status for.
#              Defaults to all sbase-box applets.
#
# Options:
#   -d <dest>  Path to directory where to install sbase symlinks. If not given,
#              symlinks are created in the same directories as busybox symlinks
#              (if busybox is installed, otherwise /usr/bin).
#   -f         If the symlink destination exists, replace it.
#   -v         Be verbose.
#   -h         Show this message and exit.
#   -V         Print ubox version and exit.
#
# Report bugs at <https://gitlab.alpinelinux.org/alpine/aports/-/issues>
#---help---
set -eu

PROGNAME='setup-sbase'
VERSION=@@VERSION@@
SBASE_BOX='/bin/sbase-box'


help() {
	sed -n '/^#---help---/,/^#---help---/p' "$0" | sed 's/^# \?//; 1d;$d;'
}

die() {
	echo "$PROGNAME: $2" >&2
	exit $1
}

bb_appletdir() {
	local path=$(/bin/busybox --list-full | grep "/$1$" 2>/dev/null) || :
	path=${path%/*}

	echo "/${path:-usr/bin}"
}

if [ $# -eq 0 ]; then
	help; exit 1
fi

ACTION=
case "${1:-}" in
	-*);;
	*) ACTION=$1; shift;;
esac

DESTDIR=
FORCE=false
VERBOSE=false
while getopts ':d:fvhV' OPT; do
	case "$OPT" in
		d) DESTDIR="$OPTARG";;
		f) FORCE=true;;
		v) VERBOSE=true;;
		h) help; exit 0;;
		V) echo "sbase $VERSION"; exit 0;;
		\?) die 10 "unknown option: -$OPTARG";;
	esac
done
shift $((OPTIND - 1))

[ "$ACTION" ] || { ACTION=${1:-}; shift; }
[ "$ACTION" ] || die 10 "invalid arguments, missing <action> (see $PROGNAME -h)"

[ -x $SBASE_BOX ] || die 10 "ERROR: $SBASE_BOX does not exist or is not executable!"

[ $# -eq 0 ] && set -- $($SBASE_BOX)

rc=0
for applet in "$@"; do
	applet_link="${DESTDIR:-$(bb_appletdir $applet)}/$applet"

	case "$ACTION" in
		install)
			[ "$applet_link" -ef "$SBASE_BOX" ] && continue

			if [ -e "$applet_link" ] && ! $FORCE; then
				$VERBOSE && echo "Skipping $applet - file $applet_link exists" >&2
				continue
			fi

			$VERBOSE && echo "Creating symlink $applet_link -> $SBASE_BOX"
			ln -fs "$SBASE_BOX" "$applet_link" || rc=11
		;;
		uninstall)
			if [ "$applet_link" -ef "$SBASE_BOX" ]; then
				$VERBOSE && echo "Removing $applet_link"
				rm "$applet_link" || rc=11
			fi
		;;
		status)
			state=
			if [ "$applet_link" -ef "$SBASE_BOX" ]; then
				state='installed'
			elif [ -e "$applet_link" ]; then
				state="not-installed ($applet_link exists)"
			else
				state='not-installed'
			fi
			printf '%-15s%s\n' "$applet" "$state"
		;;
	esac
done

if [ "$ACTION" = 'uninstall' ] && [ -x /bin/busybox ]; then
	# Restore possibly overwritten busybox symlinks.
	/bin/busybox --install -s
fi

exit $rc
